package com.zzty.txj1.controller;


import com.zzty.txj1.entity.WxConfigInfo;
import com.zzty.txj1.util.Sha1Util;
import com.zzty.txj1.util.WeiChatUtil;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

@Controller
@RequestMapping("/page")
public class PageController {
    private static final Logger logger = LoggerFactory.getLogger(PageController.class);

    private static String ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=";


    @RequestMapping("/login")
    public String login(HttpServletRequest request, ModelMap model){
        logger.info("page--controller ============ login");

        String code=request.getParameter("code");
        logger.info("code ======="+code);
        String openId=WeiChatUtil.getOpenId(code);
        logger.info("openId ======="+openId);

        //response.sendRedirect("/html/login.html");
        return "login";
    }
    @RequestMapping("/operateEvent")
    public String operateEvent(){
        return "operateEvent";
    }

    @RequestMapping("/bangDingToUser")
    public String getOpenId(HttpServletRequest request)throws Exception{
        logger.info("page--controller ============ bangDingToUser");

        String code=request.getParameter("code");
        logger.info("page--controller code ======="+code);
        String openId=WeiChatUtil.getOpenId(code);
        logger.info("page--controller ============ openId="+openId);
        request.getSession().setAttribute("openId",openId);
        logger.info("page--controller ============ url="+request.getRequestURI());
        logger.info("page--controller ============ url2="+request.getServletPath());
        logger.info("page--controller ============ url3="+request.getQueryString());
        logger.info("page--controller ============ url="+request.getRequestURI());
        String param = request.getQueryString();
        String url = request.getServletPath();//获取请求路径（不带参数）
        if(param!=null){
            url = url+"?"+param;//组合成完整请求URL
        }
        String projectnameP = request.getContextPath();
        String projectName = projectnameP.substring(projectnameP.lastIndexOf('/')+1,projectnameP.length());  //获取工程名,如testW
        if(!"".equals(projectName)){
            projectName ="/"+projectName;
        }
        String port = String.valueOf(request.getServerPort());//获取端口号
        if(!"80".equals(port)){//不是80端口时需加端口号
            port = ":"+port;
        }else{
            port = "";
        }
        String strBackUrl = "http://" + request.getServerName()+port+projectName+url;
        logger.info("page--controller strBackUrl ======="+strBackUrl);


        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");
        SortedMap<String, String> finalpackage = new TreeMap<String, String>();
        String timestamp = Sha1Util.getTimeStamp();
        finalpackage.put("timestamp", timestamp);
        finalpackage.put("noncestr", nonce_str);
        String ticket = WeiChatUtil.getjsApiTicket(ticketUrl, WeiChatUtil.getAccessToken());
        finalpackage.put("jsapi_ticket", ticket);
        finalpackage.put("url", strBackUrl);

        String signature = Sha1Util.createSHA1Sign(finalpackage);
        logger.info("page--controller timestamp ======="+timestamp);
        logger.info("page--controller noncestr ======="+nonce_str);
        logger.info("page--controller signature ======="+signature);
        logger.info("page--controller jsapi_ticket ======="+ticket);


        WxConfigInfo wxConfigInfo =new WxConfigInfo();
        wxConfigInfo.setNonceStr(nonce_str);
        wxConfigInfo.setSignature(signature);
        wxConfigInfo.setTimeStamp(timestamp);
        request.getSession().setAttribute("wxConfigInfoMap",wxConfigInfo);
        return "bindToUser";
    }


    @RequestMapping("/openMap")
    public String myPage(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {
        logger.info("page--controller ============ openMap");
        logger.info("page--controller url ======="+request.getRequestURI());
        logger.info("page--controller url2 ======="+request.getServletPath());
        logger.info("page--controller url3 ======="+request.getQueryString());
        String param = request.getQueryString();
        String url = request.getServletPath();//获取请求路径（不带参数）
        if (param != null) {
            url = url + "?" + param;//组合成完整请求URL
        }
        String projectnameP = request.getContextPath();
        String projectName = projectnameP.substring(projectnameP.lastIndexOf('/') + 1, projectnameP.length());  //获取工程名,如testW
        if (!"".equals(projectName)) {
            projectName = "/" + projectName;
        }
        String port = String.valueOf(request.getServerPort());//获取端口号
        if (!"80".equals(port)) {//不是80端口时需加端口号
            port = ":" + port;
        } else {
            port = "";
        }
        String strBackUrl = "http://" + request.getServerName() + port + projectName + url;
        System.out.println("strBackUrl  " + strBackUrl);

        String code = request.getParameter("code");
        String openId = WeiChatUtil.getOpenId(code);
        request.getSession().setAttribute("openId", openId);
        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");
        SortedMap<String, String> finalpackage = new TreeMap<String, String>();
        String timestamp = Sha1Util.getTimeStamp();
        finalpackage.put("timestamp", timestamp);
        finalpackage.put("noncestr", nonce_str);
        String ticket = WeiChatUtil.getjsApiTicket(ticketUrl, WeiChatUtil.getAccessToken());
        //String ticket = "";
        finalpackage.put("jsapi_ticket", ticket);
        finalpackage.put("url", strBackUrl);

        String signature = Sha1Util.createSHA1Sign(finalpackage);
//		model.addAttribute("timestamp ",timestamp);
        logger.info("page--controller timestamp ======="+timestamp);
        logger.info("page--controller noncestr ======="+nonce_str);
        logger.info("page--controller signature ======="+signature);
        logger.info("page--controller jsapi_ticket ======="+ticket);



        WxConfigInfo wxConfigInfo = new WxConfigInfo();
        wxConfigInfo.setNonceStr(nonce_str);
        wxConfigInfo.setSignature(signature);
        wxConfigInfo.setTimeStamp(timestamp);
        request.getSession().setAttribute("wxConfigInfoMap", wxConfigInfo);



        return "clock";
    }

    @RequestMapping("/sport")
    public String sport(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {
        logger.info("page--controller ============ sport");
        logger.info("page--controller url ======="+request.getRequestURI());
        logger.info("page--controller url2 ======="+request.getServletPath());
        logger.info("page--controller url3 ======="+request.getQueryString());

        String param = request.getQueryString();
        String url = request.getServletPath();//获取请求路径（不带参数）
        if (param != null) {
            url = url + "?" + param;//组合成完整请求URL
        }
        String projectnameP = request.getContextPath();
        String projectName = projectnameP.substring(projectnameP.lastIndexOf('/') + 1, projectnameP.length());  //获取工程名,如testW
        if (!"".equals(projectName)) {
            projectName = "/" + projectName;
        }
        String port = String.valueOf(request.getServerPort());//获取端口号
        if (!"80".equals(port)) {//不是80端口时需加端口号
            port = ":" + port;
        } else {
            port = "";
        }
        String strBackUrl = "http://" + request.getServerName() + port + projectName + url;
        logger.info("page--controller strBackUrl ======="+strBackUrl);

        String code = request.getParameter("code");
        String openId = WeiChatUtil.getOpenId(code);
        request.getSession().setAttribute("openId", openId);
        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");
        SortedMap<String, String> finalpackage = new TreeMap<String, String>();
        String timestamp = Sha1Util.getTimeStamp();
        finalpackage.put("timestamp", timestamp);
        finalpackage.put("noncestr", nonce_str);
        String ticket = WeiChatUtil.getjsApiTicket(ticketUrl, WeiChatUtil.getAccessToken());
        finalpackage.put("jsapi_ticket", ticket);
        finalpackage.put("url", strBackUrl);

        String signature = Sha1Util.createSHA1Sign(finalpackage);
        logger.info("page--controller timestamp ======="+timestamp);
        logger.info("page--controller noncestr ======="+nonce_str);
        logger.info("page--controller signature ======="+signature);
        logger.info("page--controller jsapi_ticket ======="+ticket);


        WxConfigInfo wxConfigInfo = new WxConfigInfo();
        wxConfigInfo.setNonceStr(nonce_str);
        wxConfigInfo.setSignature(signature);
        wxConfigInfo.setTimeStamp(timestamp);
        request.getSession().setAttribute("wxConfigInfoMap", wxConfigInfo);

        return "sport";
    }

    @RequestMapping("/todayRecord")
    public String todayRecord(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {
        logger.info("page--controller ============ todayRecord");
        logger.info("page--controller url ======="+request.getRequestURI());
        logger.info("page--controller url2 ======="+request.getServletPath());
        logger.info("page--controller url3 ======="+request.getQueryString());

        String param = request.getQueryString();
        String url = request.getServletPath();//获取请求路径（不带参数）
        if (param != null) {
            url = url + "?" + param;//组合成完整请求URL
        }
        String projectnameP = request.getContextPath();
        String projectName = projectnameP.substring(projectnameP.lastIndexOf('/') + 1, projectnameP.length());  //获取工程名,如testW
        if (!"".equals(projectName)) {
            projectName = "/" + projectName;
        }
        String port = String.valueOf(request.getServerPort());//获取端口号
        if (!"80".equals(port)) {//不是80端口时需加端口号
            port = ":" + port;
        } else {
            port = "";
        }
        String strBackUrl = "http://" + request.getServerName() + port + projectName + url;
        logger.info("page--controller strBackUrl ======="+strBackUrl);

        String code = request.getParameter("code");
        String openId = WeiChatUtil.getOpenId(code);
        request.getSession().setAttribute("openId", openId);
        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");
        SortedMap<String, String> finalpackage = new TreeMap<String, String>();
        String timestamp = Sha1Util.getTimeStamp();
        finalpackage.put("timestamp", timestamp);
        finalpackage.put("noncestr", nonce_str);
        String ticket = WeiChatUtil.getjsApiTicket(ticketUrl, WeiChatUtil.getAccessToken());
        finalpackage.put("jsapi_ticket", ticket);
        finalpackage.put("url", strBackUrl);

        String signature = Sha1Util.createSHA1Sign(finalpackage);
//		model.addAttribute("timestamp ",timestamp);
        logger.info("page--controller timestamp ======="+timestamp);
        logger.info("page--controller noncestr ======="+nonce_str);
        logger.info("page--controller signature ======="+signature);
        logger.info("page--controller jsapi_ticket ======="+ticket);


        WxConfigInfo wxConfigInfo = new WxConfigInfo();
        wxConfigInfo.setNonceStr(nonce_str);
        wxConfigInfo.setSignature(signature);
        wxConfigInfo.setTimeStamp(timestamp);
        request.getSession().setAttribute("wxConfigInfoMap", wxConfigInfo);

        return "todayRecord";
    }


    @RequestMapping("/luShu")
    public String luShu(HttpServletRequest request,HttpServletResponse response, ModelMap model)throws  Exception {
        return "route";
    }


        public static JSONObject getWechatUserInfo(String openId, String token){
            logger.info("page--controller ============ getWechatUserInfo");

            String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+token+"&openid="+openId;
        JSONObject result=null;
        HttpClient client = new HttpClient();
        GetMethod get = new GetMethod(url);
        try {
            client.executeMethod(get);
            String returnJson=get.getResponseBodyAsString();
            returnJson = new String(returnJson.getBytes("ISO8859_1"),"UTF-8");
            result = JSONObject.fromObject(returnJson);

            if(result.containsKey("nickname"))
                return result;
            else
                return result;
        }catch (Exception e) {}

        return result;
    }
    @RequestMapping("/getLocation")
    public String getLocation(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {
        logger.info("page--controller ============ getLocation");
        logger.info("page--controller url ======="+request.getRequestURI());
        logger.info("page--controller url2 ======="+request.getServletPath());
        logger.info("page--controller url3 ======="+request.getQueryString());
        String param = request.getQueryString();
        String url = request.getServletPath();//获取请求路径（不带参数）
        if (param != null) {
            url = url + "?" + param;//组合成完整请求URL
        }
        String projectnameP = request.getContextPath();
        String projectName = projectnameP.substring(projectnameP.lastIndexOf('/') + 1, projectnameP.length());  //获取工程名,如testW
        if (!"".equals(projectName)) {
            projectName = "/" + projectName;
        }
        String port = String.valueOf(request.getServerPort());//获取端口号
        if (!"80".equals(port)) {//不是80端口时需加端口号
            port = ":" + port;
        } else {
            port = "";
        }
        String strBackUrl = "http://" + request.getServerName() + port + projectName + url;
        logger.info("page--controller strBackUrl ======="+strBackUrl);

        String code = request.getParameter("code");
        String openId = WeiChatUtil.getOpenId(code);
        request.getSession().setAttribute("openId", openId);
        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");
        SortedMap<String, String> finalpackage = new TreeMap<String, String>();
        String timestamp = Sha1Util.getTimeStamp();
        finalpackage.put("timestamp", timestamp);
        finalpackage.put("noncestr", nonce_str);
        String ticket = WeiChatUtil.getjsApiTicket(ticketUrl, WeiChatUtil.getAccessToken());
        //String ticket = "";
        finalpackage.put("jsapi_ticket", ticket);
        finalpackage.put("url", strBackUrl);

        String signature = Sha1Util.createSHA1Sign(finalpackage);
//		model.addAttribute("timestamp ",timestamp);
        logger.info("page--controller timestamp ======="+timestamp);
        logger.info("page--controller noncestr ======="+nonce_str);
        logger.info("page--controller signature ======="+signature);
        logger.info("page--controller jsapi_ticket ======="+ticket);


        WxConfigInfo wxConfigInfo = new WxConfigInfo();
        wxConfigInfo.setNonceStr(nonce_str);
        wxConfigInfo.setSignature(signature);
        wxConfigInfo.setTimeStamp(timestamp);
        request.getSession().setAttribute("wxConfigInfoMap", wxConfigInfo);



        return "map";
    }
    @RequestMapping("/ranking")
    public String ranking(HttpServletRequest request)throws Exception{
        logger.info("page--controller ============ ranking");

        String code=request.getParameter("code");
        logger.info("page--controller code ======="+code);
        String openId=WeiChatUtil.getOpenId(code);
        logger.info("page--controller openId ======="+openId);
        request.getSession().setAttribute("openId",openId);
        logger.info("page--controller url ======="+request.getRequestURI());
        logger.info("page--controller url2 ======="+request.getServletPath());
        logger.info("page--controller url3 ======="+request.getQueryString());
        String param = request.getQueryString();
        String url = request.getServletPath();//获取请求路径（不带参数）
        if(param!=null){
            url = url+"?"+param;//组合成完整请求URL
        }
        String projectnameP = request.getContextPath();
        String projectName = projectnameP.substring(projectnameP.lastIndexOf('/')+1,projectnameP.length());  //获取工程名,如testW
        if(!"".equals(projectName)){
            projectName ="/"+projectName;
        }
        String port = String.valueOf(request.getServerPort());//获取端口号
        if(!"80".equals(port)){//不是80端口时需加端口号
            port = ":"+port;
        }else{
            port = "";
        }
        String strBackUrl = "http://" + request.getServerName()+port+projectName+url;
        logger.info("page--controller strBackUrl ======="+strBackUrl);


        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");
        SortedMap<String, String> finalpackage = new TreeMap<String, String>();
        String timestamp = Sha1Util.getTimeStamp();
        finalpackage.put("timestamp", timestamp);
        finalpackage.put("noncestr", nonce_str);
        String ticket = WeiChatUtil.getjsApiTicket(ticketUrl, WeiChatUtil.getAccessToken());
        finalpackage.put("jsapi_ticket", ticket);
        finalpackage.put("url", strBackUrl);

        String signature = Sha1Util.createSHA1Sign(finalpackage);
        logger.info("page--controller timestamp ======="+timestamp);
        logger.info("page--controller noncestr ======="+nonce_str);
        logger.info("page--controller signature ======="+signature);
        logger.info("page--controller jsapi_ticket ======="+ticket);


        WxConfigInfo wxConfigInfo =new WxConfigInfo();
        wxConfigInfo.setNonceStr(nonce_str);
        wxConfigInfo.setSignature(signature);
        wxConfigInfo.setTimeStamp(timestamp);
        request.getSession().setAttribute("wxConfigInfoMap",wxConfigInfo);
        return "ranking";
    }
}
